<template>

  <div >
    <!--内容区+侧边栏+头部-->
    <el-container>
      <!--侧边栏-->

      <el-aside
          :width="asideWidth"
          style="
          min-height: 100vh;
          background-color: #eeeeee ;
          margin-bottom: 5px;

          border-radius: 8px ;
          box-shadow: 2px 0 3px rgba(0, 0, 0, 0.4);"
      >

        <div
            style="background: white;
            height: 65PX;
            width: 100%;
            line-height: 60PX;
            color: white;
            display: flex;
            justify-content: center;
            align-items: center;"
        >
          <img src="../assets/logo 11.png" alt="logo" style="height: 50px;width: 50px;border-radius: 8px;">

          <img src="../assets/logo 1.png" alt="logo"  class="logo-title"  v-show="!isCollapse">

        </div>
        <el-menu  :collapse="isCollapse" :collapse-transition="false" router style="background-color:#eeeeee" :default-active=  "$route.path">
          <el-menu-item index="/index1">
            <el-icon :size="20">  <House/></el-icon>
            <span style="margin-left: 2px">系统首页</span>
          </el-menu-item>
          <el-menu-item index="/order1">
            <el-icon :size="20">  <Shop/></el-icon>
            <span style="margin-left: 2px">订单管理</span>
          </el-menu-item>

          <el-menu-item index="/member1" >
            <el-icon :size="20">  <Avatar/></el-icon>
            <span style="margin-left: 2px">会员管理</span>
          </el-menu-item>

          <el-menu-item index="/goods">
            <el-icon :size="20">  <DataBoard/></el-icon>
            <span style="margin-left: 2px">商品管理</span>
          </el-menu-item>

          <el-menu-item index="/data1">
            <el-icon :size="20">  <DataAnalysis/></el-icon>
            <span style="margin-left: 2px">数据分析</span>
          </el-menu-item>

          <el-sub-menu index="11">
            <template #title>
              <el-icon :size="20" style="margin-left: 5px"><setting/></el-icon>
              <span >个人中心</span>
            </template>

            <el-menu-item index="/self1" >个人信息</el-menu-item>
            <el-menu-item index="/change">密码修改</el-menu-item>
          </el-sub-menu>

        </el-menu>

      </el-aside>
      <!--内容区+头部-->
      <el-container>
        <!-- 头部 -->
        <el-header>
          <!-- 折叠按钮-->
          <i  style="width: 26px;align-content: center;" @click="handleCollapse"> <Menu/> </i>

          <!--页眉栏-->
          <el-breadcrumb separator-class="el-icon-arrow-right" style="width:auto;align-content: center;margin-left: 10px">
            <el-breadcrumb-item :to="{path:'/index1'}">系统首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/order1'}">订单管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/member1'}">会员管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/goods'}">商品管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{path:'/data1'}">数据分析</el-breadcrumb-item>
            <el-breadcrumb-item >Doing</el-breadcrumb-item>
          </el-breadcrumb>

          <!-- 头像 -->
          <div style="flex:1;  display: flex; align-items: center;justify-content: flex-end;">
            <el-dropdown>
      <span >
        <img src="../assets/touxiang.png" alt="touxiang" style="height: 50px;width: 50px;">
        <span style="font-family: 华文楷体;font-size:20px">管理</span>
        <el-icon ><arrow-down /></el-icon>
      </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="$router.push('/self1')" target="_self">个人中心</el-dropdown-item>
                  <el-dropdown-item @click="outAccount">退出账号</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

        </el-header>



        <!--内容区-->
        <el-main class="custom-main">
          <div style="display: flex; flex-direction: column; height: 100vh;width: 100%">
            <!-- 搜索框行 -->
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <div style="display: flex; align-items: center;margin-bottom: 10px;">
                <el-input
                    v-model="input1"
                    style="width: 200px; margin-right: 10px;"
                    placeholder="请输入 商品"
                ></el-input>
                <el-button   @click="getgoodId(input1)" class="ml-5" type="primary">搜索</el-button>
                <el-button   @click="clearInput" class="ml-5" type="primary">显示全部</el-button>
                <el-button @click="start" type="primary"><i class="el-icon-plus"></i> 新增</el-button>
              </div>
            </div>

            <!-- 按钮行 -->

            <div style="flex: 1; display: flex; flex-direction: column; overflow-y: auto;">
              <el-table
                  :data="tableData1"
                  border stripe
                  :header-cell-class-name="headerBg"
                  width="100%"
              >
                <!-- 日期列 -->
                <el-table-column type="selection" width="55" />

                <el-table-column prop="commodityId" label="商品ID" width="auto">
                </el-table-column>


                <el-table-column prop="commodityName" label="商品名称" width="auto">
                </el-table-column>

                <el-table-column prop="commodityPrice" label="商品价格" width="auto">
                </el-table-column>

                <el-table-column prop="commodityCategory" label="商品类别">
                </el-table-column>

                <el-table-column prop="commodityInventory" label="库存" width="auto">
                </el-table-column>

                <el-table-column prop="commodityDescribe" label="商品描述" width="auto">
                </el-table-column>

                <el-table-column label="操作" width="auto" min-width="100px">
                  <!-- 使用 v-slot 替代 slot-scope -->
                  <template v-slot="scope">
                    <el-button type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="danger" plain @click="handleDelete(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <el-dialog
                  v-model="centerDialogVisible"
                  width="500px"
                  center
              >
                <!-- 表单 -->
                <el-form :model="form" label-width="120px">
                  <el-form-item label="商品ID(自动)" >
                    <el-input v-model="form.commodityId"  :disabled="true"/> <!-- 添加.number修饰符，假设库存是数字 -->
                  </el-form-item>
                  <el-form-item label="商品">
                    <el-input v-model="form.commodityName" /> <!-- 添加.number修饰符，假设库存是数字 -->
                  </el-form-item>
                  <el-form-item label="商品价格">
                  <el-input v-model.number="form.commodityPrice"  /> <!-- 改为textarea以支持多行文本 -->
                  </el-form-item>
                  <el-form-item label="商品类型">
                    <el-select
                        v-model="form.commodityCategory"
                        placeholder="Select"
                        size="large"
                        style="width: 500px"
                    >
                      <el-option
                          v-for="item in options"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="库存">
                    <el-input v-model="form.commodityInventory"  /> <!-- 改为textarea以支持多行文本 -->
                  </el-form-item>
                  <el-form-item label="商品描述">
                  <el-input v-model="form.commodityDescribe" />
                </el-form-item>
                  <div slot="footer" class="dialog-footer" style="align-content: center;justify-content: center;display: flex; ">
                    <el-button type="primary" @click="sendSaveRequest">提交</el-button>
                    <el-button @click="centerDialogVisible = false">取消</el-button>
                  </div>
                </el-form>
              </el-dialog>



            </div>

            <div style="padding: 10px 0; text-align: center;">
              <el-pagination
                  :page-sizes="[5, 10, 15, 20]"
                  :page-size="10"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="400">
              </el-pagination>
            </div>
          </div>
        </el-main>

      </el-container>

    </el-container>

  </div>
</template>

<script setup>
import { Avatar, School, Share, Shop } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';
import {ref, onMounted, reactive} from 'vue';
import axios from "axios";
const tableData1 = ref([]);


//获取全部
const getall = async () => {
  try {
    const response = await axios.get('http://localhost:918/commodity/getall');
    tableData1.value = response.data;
  } catch (error) {
    console.error('Error fetching data:', error.message);
    if (error.response?.status === 404) {
      console.error('Data not found');
      // 可以考虑在这里通知用户数据未找到
      ElMessage.error('Data not found');
    }
  }
};
onMounted(getall);

//删除
async function handleDelete(row) {
  // 发送DELETE请求到服务器以删除指定的订单
  try {
    // 修正了await的用法，并去掉了检查响应状态的注释，因为我们将通过axios的错误处理来捕获非200状态
    await axios.delete(`http://localhost:918/commodity/delete/${row.commodityId}`);

    // 查找并删除前端数组中的元素（这里假设使用name作为键可能不是最佳实践，但按照您的代码进行）
    const index = tableData1.value.findIndex(item => item.commodityId === row.commodityId);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
      // 通知用户数据已删除
      ElMessage.success('Data deleted successfully');
    } else {
      // 可选：如果数组中找不到元素，可以通知用户或进行其他处理
      // 但在这个场景下，因为我们已经从服务器删除了数据，所以可能不需要额外通知
      // 除非您期望前端数组和服务器数据完全同步
      console.warn('Data not found in local array, but deleted from server');
    }
  } catch (error) {
    // 处理请求过程中的错误（包括网络错误和服务器返回的非2xx状态码）
    // axios会自动将非2xx响应视为错误并抛出异常
    ElMessage.error(`Failed to delete order: ${error.message}`);
  }
}



const activeName = ref('1');
const isCollapse = ref(false);
const asideWidth = ref('200px');

const handleCollapse = () => {
  isCollapse.value = !isCollapse.value;
  asideWidth.value = isCollapse.value ? '64px' : '200px';
  ElMessage({
    message: isCollapse.value ? 'Collapsed' : 'Expanded',
    type: 'info'
  });
};



//表单
const form = reactive({
  commodityId: 0,
  name: '',
  price: 0,
  category: '', // 假设价格默认为0
  inventory:0  ,// 假设库存默认为0
  description: '',



});
let centerDialogVisible = ref(false);

//编辑
const handleEdit = (row) => {
  // 注意：这种方法会丢失 Vue 的响应性追踪，因为你是通过非响应式方式赋值
  // 更好的做法是只更新需要的属性，或者使用 Vue 3 的 provide/inject 机制结合响应式引用传递
  //
  // // 更好的实践：只更新需要的属性
  form.commodityId= row.commodityId;
  form.commodityName= row.commodityName;
  form.commodityPrice= row.commodityPrice // 假设价格默认为0
  form.commodityCategory=row.commodityCategory,
      form.commodityInventory=row.commodityInventory, // 假设库存默认为0
      form.commodityDescribe=row.commodityDescribe,
  // 显示表单弹窗（假设你有一个这样的状态来控制）
  centerDialogVisible.value = true; // 你可能需要这个来控制表单的显示
};


const options = [
  {
    value: '食品类',
    label: '食品类'
  },
  {
    value: '日杂类',
    label: '日杂类'
  },
  {
    value: '电子',
    label: '电子'
  },
  {
    value: '文具',
    label: '文具'
  },
  {
    value: '服饰',
    label: '服饰'
  },
  {
    value: '玩具',
    label: '玩具'
  },
  {
    value: '饮品',
    label: '饮品'
  },
]



//开启弹窗
function start() {
  Object.keys(form).forEach(key => {
    form[key] = ''; // 清空表单，假设所有字段都是字符串类型
  });
  form.id = null; // 确保id被清空
  centerDialogVisible.value = true;
}

//退出账号
function outAccount() {
  window.sessionStorage.removeItem('token');
  window.location.href = '/';
}

//提交功能
function sendRequest(url, method, data) {
  return axios({
    url,
    method,
    data
  });
}


//提交
function sendSaveRequest() {
  // 使用axios发送POST请求到服务器上的'http'路径，同时发送form数据
  const url = form.commodityId? 'http://localhost:918/commodity/update':'http://localhost:918/commodity/';
  const method = form.commodityId ? 'PUT' : 'POST';
  sendRequest(url, method, form)
      // 当请求成功时，执行以下操作
      .then(res => {
        // 检查响应数据中的code是否为'200'，表示操作成功
        if (res.data.code === '200') {
          // 使用Element Plus的ElMessage组件显示成功消息
          ElMessage.success('编辑成功');
          getall();
          // 调用getall函数，假设该函数用于重新加载或更新数据列表
          // 将表单弹窗的显示状态设置为false，以关闭弹窗
          centerDialogVisible.value = false;
        } else {
          // 如果操作未成功，使用Element Plus的ElMessage组件显示错误信息
          ElMessage.success('新建成功');
          centerDialogVisible.value = false;
          getall();
        }
      })
      // 当请求失败时，执行以下操作
      .catch(error => {
        // 在控制台输出错误信息
        console.error('请求失败:', error);
        // 使用Element Plus的ElMessage组件向用户显示请求失败的通用错误消息
        ElMessage.error('请求失败，请稍后再试');
      });
}



//输入框内容
const input1 = ref('')
//根据ID搜索
async function getgoodId(input1) {
  try {
    const response = await axios.get(`http://localhost:918/commodity/search?keyword=${encodeURIComponent(input1)}`);

    tableData1.value = response.data;
  }
  catch (error) {
    console.error('Error fetching data:', error.message);
    if (error.response?.status === 404) {
      console.error('Data not found');
      // 可以考虑在这里通知用户数据未找到
      ElMessage.error('Data not found');
    }
  }
}

// 清空输入框
async function clearInput() {
  input1.value = '';
  // 获取所有订单数据
  await getall();
}






</script>
<style scoped>
/* 你可以在这里添加CSS样式 */
.el-menu-item:hover{
  color:#fff;
}

.el-menu-item{
  margin-bottom: 5px;
  margin-top: 5px;
  margin-left: 5px;
  margin-right: 5px;
  border-radius: 8px ;
}
.custom-main {
  min-height: 100vh;
  background-color:#eeeeee;
  display: flex;
  height: 100%;
  margin-bottom: 5px;
  margin-top: 5px;
  margin-left: 5px;
  margin-right: 5px;
  border-radius: 8px ;
  box-shadow: 2px 0 3px rgba(0, 0, 0, 0.4); /* 右侧阴影效果 */
}

.logo-title{
  height: 50px;
  width: 140px;
  border-radius: 8px;
}

.el-header {
  box-shadow: 2px 0 3px rgba(0, 0, 0, 0.4); /* 右侧阴影效果 */
  display: flex;
  align-content: center;
  margin-left: 5px;
  margin-right: 5px;
  border-radius: 8px ;
}

</style>